from flask import Flask, render_template, request, abort, send_file
import os

class Website:
    def __init__(self, name: str) -> None:
        self.app = Flask(name, static_folder="./res", template_folder="./html")
        self.funcs = {}
        # self.static_pool = {}
    
    def start(self, host: str, port: int, debug=False):
        self.app.run(host, port, debug)
    
    def load_res(self):
        # def walk(path):
        #     r = []
        #     if not os.path.isdir(path):return path
        #     for i in os.listdir(path):
        #         r.append(walk(i))
        #     return (path, r)
        # self.static_pool = walk(self.app.static_folder)
        # for i in os.listdir(self.app.static_folder):
        #     with open(os.path.join(self.app.static_folder, i), 'r', encoding='utf-8') as f:
        #         self.static_pool[i] = f.read()
        pass

    def subscribe_rule(self):
        self.funcs = {
            "/res": self.r_res,
            "/": self.r_,
            "/webchat_index": self.r_webchat_index,
            "/homepage": self.r_homepage,
            "/chatroom": self.r_chatroom,
            "/settings": self.r_settings,
        }
        for k, v in self.funcs.items():
            self.app.add_url_rule(k, v.__name__, v)
        # print(self.__class__.__dict__)
        # for k, v in self.__class__.__dict__.items():
        #     if k.startswith('r_'):
        #         self.app.add_url_rule('/'+k[2:], k, view_func=lambda: v(self))
                # self.funcs[k[2:]] = v
    
    def r_(self):
        return render_template("index.html")
    
    def r_webchat_index(self):
        return render_template("webchat.html")
    
    def r_homepage(self):
        return render_template("homepage.html")
    
    def r_chatroom(self):
        return render_template("chatroom.html")
    
    def r_settings(self):
        return render_template("settings.html")

    def r_res(self):
        # filename = request.args.get('name')
        # if filename not in self.static_pool.keys():abort(404)
        # return self.static_pool[filename]
        return self.app.send_static_file(os.path.join(self.app.static_folder, request.args.get('name')))



if __name__ == '__main__':
    application = Website('webchat')
    application.subscribe_rule()
    application.load_res()
    application.start("0.0.0.0", 4399)